package com.syqc.comlib.network

import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager

class NetChangerReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
            for (listener in listeners) {
                listener.onDisconnect(NetUtil.isAvailable(context))
            }
        }
    }

    companion object {
        private val receiver = NetChangerReceiver()
        private val listeners = mutableListOf<OnNetChangerListener>()

        fun init(application: Application) {
            application.registerReceiver(
                receiver,
                IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            )
        }


        @Synchronized
        fun addListener(listener: OnNetChangerListener) {
            listeners.add(listener)
        }

        @Synchronized
        fun removeListener(listener: OnNetChangerListener) {
            listeners.remove(listener)
        }
    }


}